package com.example.demo.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import com.example.demo.pojo.RedisData;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

// CacheUtil
@Slf4j
@Component
public class CacheUtil {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    // 没有解决缓存击穿
    public <R, ID> R get(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallBack, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        R r = dbFallBack.apply(id);
        stringRedisTemplate.opsForValue().set(key, r == null ? "" : JSONUtil.toJsonStr(r), time, unit);
        return r;
    }
    // 使用逻辑过期解决缓存击穿
    public <R, ID> R getWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallBack, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        R bean = JSONUtil.toBean((JSONObject) redisData.getData(), type);

        if (bean == null || expireTime.isBefore(LocalDateTime.now())) {
            String lockKey = "cache:lock:" + id;
            boolean isLock = lock(lockKey);
            if (isLock) {
                CACHE_REBUILD_EXECUTOR.submit(() -> {
                    try {
                        R newBean = dbFallBack.apply(id);
                        // 存入缓存
                        setWithLogicalExpire(key, newBean, time, unit);
                    } finally {
                        unlock(lockKey);
                    }
                });
            }
        }
        return bean;
    }
    // 为对象设置逻辑过期字段 并且存入缓存中
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = RedisData.builder()
                .data(value)
                .expireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)))
                .build();
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    private boolean lock(String key) {
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key, "", 1, TimeUnit.MINUTES));
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}
